﻿#region Usings
using System.Linq;

using BK.BlusinessLogic.Exceptions;
using BK.Model;
using BK.Repositories.Abstract;
using BK.Repositories.Factory;
#endregion

namespace BK.BlusinessLogic
{
    public class UsersBl
    {
        #region Readonly & Static Fields
        private readonly IUsersRepository _usersRepository;
        #endregion

        #region C'tors
        public UsersBl()
        {
            _usersRepository = RepositoryFactory.Get<IUsersRepository>();
        }

        public UsersBl(IUsersRepository usersRepository)
        {
            _usersRepository = usersRepository;
        }
        #endregion

        #region Instance Methods
        public void Add(User user)
        {
            if (_usersRepository.GetByEmail(user.Email) == null)
            {
                _usersRepository.Save(user);
                _usersRepository.Save();
            }
            else
            {
                throw new UniqueException();
            }
        }

        public User[] GetAll()
        {
            return _usersRepository.GetAll().ToArray();
        }

        public User GetByEmail(string email)
        {
            return _usersRepository.GetByEmail(email);
        }

        public void Save()
        {
            _usersRepository.Save();
        }

        public void Save(User user)
        {
            _usersRepository.Save(user);
        }

        public void Tie(User user, BestExpensesFile bestExpensesFile)
        {
            if (user.BestExpensesFiles.Where(x => x.Id == bestExpensesFile.Id).FirstOrDefault() != null)
            {
                throw new AlreadyTiedException();
            }

            user.BestExpensesFiles.Add(bestExpensesFile);
        }

        public void Tie(User user, FinancistoFile financistoFile)
        {
            if (user.FinancistoFiles.Where(x => x.Id == financistoFile.Id).FirstOrDefault() != null)
            {
                throw new AlreadyTiedException();
            }

            user.FinancistoFiles.Add(financistoFile);
        }
        #endregion
    }
}